package com.test.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import com.test.server.handler.HandlerFactory;
import com.test.server.handler.RequestResponseHandler;
import com.test.server.processor.RequestProcessor;
import com.test.server.request.Request;
import com.test.server.response.Response;
import com.test.server.response.ResponseTemplate;
import com.test.server.utils.Utils;

public class ClientHandler extends Thread{
    
    private Socket socket;
    
    public ClientHandler(Socket socket) {
        this.socket = socket;
    }
    
    @Override
    public void run() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            
            StringBuilder requestString = new StringBuilder();
            String buf = null;
            while ((buf = bufferedReader.readLine()) != null) {
                requestString.append(buf).append("\n");
            }
            
            RequestType requestType = Utils.getRequestType(requestString.toString());
            
            RequestResponseHandler handler = HandlerFactory.buildHandler(requestType);
            
            Request request = handler.buildRequest(requestString.toString());
            
            ResponseTemplate responseTemplate = RequestProcessor.processRequest(request);
            
            Response response = handler.buildResponse(responseTemplate);
            
            bufferedWriter.write(response.getContent());
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    @Override
    protected void finalize() throws Throwable {
        socket.close();
        super.finalize();
    }
    
}
